<?php
/**
 * 购物车模型管理
 * @author cjli
 *
 */   
class CartModel extends Model
{
	 
	/**
	 *获取购物车中商品列表
	 *@param boolean $is_collect 是否为收藏产品
	 */
	public static function get_cart_product_list($is_collect = false,$attribute_type=0,$pro_type='all',$display=1)
	{
		global $user;
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		}else{
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}

		$where['is_collect'] = $is_collect ? 1 : 0;
		if($attribute_type){
			$where['car_type'] = 1;
		}else{
			$where['car_type'] = 0;
		}

		if(strval($pro_type) != 'all'){
			$where['pro_type'] = $pro_type;
		}

		if($display == 0)
			$cart_db = D('cart_products_display');
	    else
	        $cart_db = D('cart_products');
	    	
		$cartInfo = array(
			'total_weight' => 0,
			'total_amount' => 0,
			'total_number' => 0,
			'is_custom' => false,
			'total_amount_normal' => 0,
		);
		$cartList = $cart_db->where($where)->order('add_time DESC')->select();
		//echo $cart_db->getLastSql()."<br>";
		// echo "<pre />";
		// echo print_r($cartList);exit;
		if($cartList){
			foreach ($cartList as &$cart){
				if($cart['pid']){
					$attr = unserialize($cart['attr']);
					$product = ProductModel::get_product_info($cart['pid']);
					//dump($product);exit;
					//**兼容原先数据  
					$product['price'] = ProductModel::get_final_price($cart['pid'], $cart['qty'], true, $attr, $cart['custom_type']);
					if($attribute_type){
						$product['goods_amount']  = $product['sell_price'] * $cart['qty'];
						$product['price'] = $product['sell_price'];
					}else{
						$product['goods_amount']  = $product['price'] * $cart['qty'];
					}  
                    //**兼容原先数据
					if($cart['price'] > 0 || $cart['pro_type'] > 0){ //兼容原先数据
						//使用购物车里的价格
						$product['price'] = $cart['price'];
	                    $product['goods_amount']  = $cart['price'] * $cart['qty'];  
					}

					$product['goods_weight']  = $product['weight'] * $cart['qty'];
					$product['goods_dingjin'] = $product['yufu_price'] * $cart['qty'];
					
						if($cart['car_type'] == 0){
							$product['goods_dingjin'] = 0;
						}
					
						if($cart['custom_type'] && is_array($attr)){
							$attrList = array();
							foreach ($attr as $attrv){
								$attr2 = explode(':', $attrv);
								$attrList[] = array(
									'attr_id' => $attr2[0],
									'attr_name' => $attr2[1],
									'product_attr_id' => $attr2[2],
									'attr_value' => $attr2[3],
								);
							}
							$product['attr'] = $attrList;
							$cartInfo['is_custom'] = true;
						}else{
							$product['attr'] = AttributeModel::get_product_attribute_List($attr);
						}
						
						//两件套 三件套 增加 附加裤子
						if(in_array($product['model_id'], array(2,18)) && $product['add_more'] == 1){
							$add_more_product = array();
							$add_more_product['name']  =  L('addPants');
							$add_more_product['price'] =  $product['pants_price'];
							$cart['add_pants'] = $add_more_product;
							if($cart['pants_qty'] > 0){
								$cartInfo['total_amount']  += $product['pants_price'] * $cart['pants_qty'];
								$cartInfo['total_amount_normal']  += $product['pants_price'] * $cart['pants_qty'];
							}
					    }else{
					    	if($cart['pants_qty'] > 0){
                                D('cart_products')->where(array('id'=>$cart['id']))->save(array('pants_qty'=>0));
					    		$cart['pants_qty'] = 0;
					    	}
					    }

						$cart['product'] = $product;
						$cartInfo['total_weight']  += $product['goods_weight'];
						$cartInfo['total_amount']  += $product['goods_amount'];
						$cartInfo['total_dingjin'] += $product['goods_dingjin'];
						if(!$cart['car_type'])
							$cartInfo['total_number']  += $cart['qty'];
                        if($cart['pro_type'] == 0){
                        	$cartInfo['total_amount_normal']  += $product['goods_amount'];
                        } 
						
					
				}
			}
			unset($cart);
	
			$cartInfo['productList'] = $cartList;
		}
	
		if(!$is_collect){
			$_SESSION['cart']['number'] = $cartInfo['total_number'];
			$_SESSION['cart']['amount'] = $cartInfo['total_amount'];
		}
		return $cartInfo;
	}
	
	/**
	 * 获取购物车中单个商品的信息
	 * @param int $cart_id 购物车ID
	 */
	public static function get_cart_product_info_by_id($cart_id)
	{
		$cart_id = intval($cart_id);
		if(!$cart_id) return false;
		
		$cart_db = D('cart_products');
		$cartInfo = $cart_db->where(array('id' => $cart_id))->find();
		return $cartInfo;
	}
	
	/**
	 * 根据商品ID获取购物车中单个商品的信息
	 * @param int $pid 商品ID
	 * @param array $attr 商品属性
	 * @param int $custom_type 定制类型
	 * @param int $pro_type 类型 0为正常商品
	 */
	public static function get_cart_product_info_by_pid($pid, $attr, $custom_type=0, $pro_type=0)
	{
		global $user;
		$pid = intval($pid);
		$cart_db = D('cart_products');
		if(!$pid && empty($data)){
			return false;
		}
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		} else {
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}
		if($pid){
			$where['pid'] = $pid;
		}
		if($attr){
			$where['attr'] = serialize($attr);
		}
		if($custom_type){
			$where['custom_type'] = intval($custom_type);
			$where['car_type'] = 0;
		}
		//if($pro_type){
			$where['pro_type'] = $pro_type;
		//}
		$cartInfo = $cart_db->where($where)->find();
		return $cartInfo;
	}
	
	/**
	 * 根据商品ID获取购物车中单个商品的信息(预售)
	 * @param int $pid 商品ID
	 * @param array $chima 商品尺码
	 */
	public static function get_cart_product_yushou_pid($pid, $chima)
	{
		global $user;
		$pid = intval($pid);
		$cart_db = D('cart_products');
		if(!$pid && empty($data)){
			return false;
		}
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		} else {
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}
		if($pid){
			$where['pid'] = $pid;
		}
		if($chima){
			$where['chima'] = $chima;
		}
		$cartInfo = $cart_db->where($where)->find();
		return $cartInfo;
	}
	
	/**
	 * 更新购物车商品信息
	 * @param int $cart_id 购物车ID
	 * @param float $price 单件价格
	 * @param int $qty 购买商品数量
	 */
	public static function update_cart_product_info($cart_id, $qty, $price, $add_pants=false, $attr=NULL)
	{
		$affected = false;
		$cart_db = D('cart_products');
		$cartInfo = self::get_cart_product_info_by_id($cart_id);
		if($cartInfo){
			if(!$add_pants){
				$data['qty'] = $qty;
               	$data['price'] = $price;
			}else{
                $data['pants_qty'] = $qty;
			}
			$data['add_time'] = time();
		    if($attr){
		    	$data['attr'] = serialize($attr);
		    }

			$affected = $cart_db->where(array('id' => $cart_id))->save($data); 
		}
		return $affected;
	}
	
	/**
   * 新增商品到购物车
   * @param array $post
   */
	public static function insert_product_to_cart($post)
	{
		global $user;
		$data = array(
			'sid' => $user['sid'],
			'user_id' => isset($user['id']) ? $user['id'] : 0,
			'pid' => isset($post['pid']) ? intval($post['pid']) : 0,
      		'qty' => isset($post['qty']) ? intval($post['qty']) : 1,
			'custom_type' => isset($post['custom_type']) ? intval($post['custom_type']) : 0,
      		'add_time' => time(),
			'chima' => trim($post['chima']),
			'car_type' => trim($post['car_type']),
      		'attr' => isset($post['attr']) && $post['attr'] ?  serialize($post['attr']) : null,
			'measure_id' => isset($post['measure_id']) ? intval($post['measure_id']) : 0,
			'match_id' => isset($post['match_id']) ? intval($post['match_id']) : 0,
			'measure_id' => $post['measure_id'],
			'pro_type' => $post['pro_type'],
			'price' => $post['price'],
		);
        if($post['add_time']){
            $data['add_time']=$post['add_time'];
        }
		$cart_db = D('cart_products');
		$last_id = $cart_db->add($data);
		return $last_id;
	}
	
	/**
	 * 删除购物车中的商品
	 * @param int $cart_id 购物车ID号
	 */
	public static function delete_cart_product($cart_id)
	{
		global $user;
		$where = array(
			//'user_id' => isset($user['id']) ? $user['id'] : 0,
			'id' => is_array($cart_id) ? array('IN', join(',', $cart_id)) : $cart_id,
		);
		if(UserModel::logged()) {
			if(is_array($cart_id)){
                foreach ($cart_id as $val) {
                	self::product_seckill_result($val);
                }
			}else{
				self::product_seckill_result($cart_id);
			}
		}
		$cart_db = D('cart_products');
		$cart_db->where($where)->delete();
		$cart_db = D('cart_products_display');
		$cart_db->where($where)->delete();

		//清衬衫活动临时代码 可全删
 		$where = array(
			'cid' => is_array($cart_id) ? array('IN', join(',', $cart_id)) : $cart_id,
		);       
		$cart_db = D('cart_products');
		$cart_db->where($where)->delete();
		$cart_db = D('cart_products_display');
		$cart_db->where($where)->delete();					
	}
	

	/**
	 * 删除购物车中的商品时秒杀名额恢复
	 * @param int $cart_id 购物车ID号
	 */
	public static function product_seckill_result($cart_id)
	{
		global $user;
		if(UserModel::logged()) {
			$cart_info = self::get_cart_product_info_by_id($cart_id);
			if($cart_info && $cart_info['pro_type']==1){
				$seckill_result_id = D('seckill_result')
				->where(array('user_id'=>$user['id'], 'pid'=>$cart_info['pid'], 'used'=>1))
				->order('id desc')
				->getField('id');
				if($seckill_result_id){
					D('seckill_result')
					->where(array('id'=>$seckill_result_id))
					->save(array('used'=>0));
				}
			}
		}
	}	

	//获取购物车中商品总数
	public static function get_cart_product_count()
	{
		global $user;
		$cart_db = D('cart_products');
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		}else{
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}
		$where['is_collect'] = 0;
		$count = $cart_db->where($where)->count();
		return $count;
	}
	
	/**
	 * 获取商品选择的属性
	 * @param array $post $_POST数据
	 */
	public static function get_product_select_attribute($post)
	{
		$attr = array();
		if(is_array($post)){
			foreach ($post as $attribute_id => $attribute_values_id)
			{
				$attribute_name = AttributeModel::get_attriubet_items($attribute_id);
				$attribute_values_name = AttributeModel::get_attribute_values_items($attribute_values_id);
				$attr[$attribute_name] = $attribute_values_name;
			}
		}
		return $attr ? $attr : null;
	}
	
	/**
   * 合并购物车
   * @param string $sid 会话ID
   */
  public static function mergeCart($sid = null)
  {
  	global $user;
  	if (!session('user_id')) {
  		return false;
  	}
  	if (!isset($sid)) {
      $sid = $user['sid'];
    }
  	$cart_db = D('cart_products');
    $affected = $cart_db->where(array('sid' => $sid,'user_id'=>array('eq',0)))->save( array('user_id' => session('user_id')));
    return (boolean)$affected;
  }
	
	/**
   * 清除会话购物车
   * @param string $sid 会话ID
   */
  public static function clearCart($sid = null,$dbname = 'cart_products')
  {
    global $user;
    $where = array();
    if(isset($user['id']) && $user['id']){
    	$where['user_id'] = $user['id'];
    }else{
     $where['sid'] = $sid ? $sid : $user['sid'];
    }
     $where['is_collect'] = 0;
    $cart_db = D($dbname);
    $cart_db->where($where)->delete();
    unset($_SESSION['cart']);
  }
  
  /**
   * 购物车配套（定制）
   * @param string $aid 产品类型ID
   */
  public static function product_mating($aid = null)
  {
	$product_db = D('product');
	$where['model_id']  = array('neq',$aid);
	$where['attribute_type']  = array('neq',1);
	$product_db->field('id');
	$productInfo = $product_db->where($where)->order('id DESC')->find();
	if($productInfo['id']){
		$product = ProductModel::get_product_info($productInfo['id']);
	}
	return $product;
  }
  
  /**
   * 购物车配套（正常）
   * @param string $aid 产品类型ID
   */
  public static function product_mating_normal()
  {
  	global $language_id;
	$where = array(
		'language_id' => $language_id ? $language_id : C('language_id'),
		'is_delete' => 0,
		'display' => 1,
		'attribute_type' =>1,
	);
			
	$product_db = D('product');
	$product_db->join('product_items ON product_items.product_id = product.id');
	$product_db->limit(0, 2);
	$productList = $product_db->order('rand()')->where($where)->select();
	return $productList;
  }

  /**
   * 判断是否符合‘三件衬衫免价格最低一件’
   * @param int $num 衬衫件数
   * @param float $minPrice 最低价格
   */
  public static function cart_shirt_free()
  {
     //获取购物车数据
     $cartInfo = self::get_cart_product_list(false, 0, 0);
     //提出件数，价格
     $minPrice = 0;
     $num = 0;
     foreach ($cartInfo['productList'] as $key => $value) {
     	//产品分类是否衬衫
     	$catid = $value['product']['catid'];
     	$parentid = D('category')->where('id='.$catid)->getField('parentid');
		//父id=2062为衬衫
		if($parentid == 2062 || $catid == 2062){  
            if($minPrice == 0 || $value['product']['advanced_price'] < $minPrice)
                $minPrice = $value['product']['advanced_price'];
            $num += $value['qty'];
		}
     }
     return array('num'=>$num, 'minPrice'=>$minPrice);
  }
/*
 *  9月营销活动 判断是否符合使用套餐优惠码 条件
 */
  public static function cart_package_free($coupon){
      global  $user;
        $package = array(
            //套餐列表array('西装id'-suit_id,'衬衫id'-shirt_id,'配饰id'-accessories_id)
            '1' => array('suit_id'=>374,'shirt_id'=>376,'accessories_id'=>250),
            '2' => array('suit_id'=>198,'shirt_id'=>312,'accessories_id'=>366),
            '3' => array('suit_id'=>180,'shirt_id'=>314,'accessories_id'=>367),
            '4' => array('suit_id'=>387,'shirt_id'=>131,'accessories_id'=>549),
            '5' => array('suit_id'=>445,'shirt_id'=>471,'accessories_id'=>210),             
        );
        $coupon_list = array(//优惠码 及 优惠价格
            '1'=> array('code'=>'BUNDLE1','money'=>93.4),
            '2'=> array('code'=>'BUNDLE2','money'=>83.4),
            '3'=> array('code'=>'BUNDLE3','money'=>83.4),
            '4'=> array('code'=>'BUNDLE4','money'=>65.4),
            '5'=> array('code'=>'BUNDLE5','money'=>91.4)
        );
        if (isset($user['id']) && $user['id']) {
                $where['user_id'] = $user['id'];
        }else{
                $where['user_id'] = 0;
                $where['sid'] = $user['sid'];
        }
        $where['car_type'] = 0;
        //获得当前购物车内商品的信息
        $cartInfo = M('cart_products')->where($where)->select();
        
        $arr2 = array();//获得购物车订单id
        foreach($cartInfo as $k=>$v){
           $arr2[] = $v['pid'];//购物车转化成商品id一维数组
        }

        //通过购物车内的id 和套餐内id 比较 如果 套餐内的id数组 完全是购物车内数组的子集 就说明可以使用该优惠码
        foreach($package as $k1=>$v1){
            $result = array_diff($v1, $arr2);
            if(!$result){//返回false,就是没有任何不同 表示$v1的数组项$arr2里都有  $v1完全就是$arr2的子集 ，说明购物车内使用了套餐内规定的搭配
                if($coupon == $coupon_list[$k1]['code']){//同时判断是否使用了指定的优惠码
                   return $coupon_list[$k1];
                }
            }
        }
    return false;
  }

  	/**
	 * 删除指定pro_type的商品
	 * @param int $pro_type 购物车类型id
	 */
	public static function delete_cart_product_pro_type($pro_type)
	{
		$cartList = self::get_cart_product_pro_type($pro_type);
		foreach ($cartList as $key => $val) {
			self::delete_cart_product($val['id']);
		}
	}

	/**
	 * 获取指定pro_type的商品
	 * @param int $pro_type 购物车类型id
	 */
	public static function get_cart_product_pro_type($pro_type)
	{
		global $user;
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		}else{
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}

		$where['pro_type'] = $pro_type;
		$cart_db = D('cart_products');
		$cartList = $cart_db->field('id')->where($where)->order('add_time DESC')->select();
        return $cartList;
	}

  /**
   * 判断查询某个类别在购物车里的价格总数
   * @param $Price 总价格
   */
  public static function cart_type_price($cat_id)
  {
     //获取购物车数据
     $cartInfo = self::get_cart_product_list(false, 0, 0);
     //提出件数，价格
     $price = 0;
     foreach ($cartInfo['productList'] as $key => $value) {
     	//产品分类是否一致
     	$catid = $value['product']['catid'];
     	$parentid = D('category')->where('id='.$catid)->getField('parentid');
		if($parentid == $cat_id || $catid == $cat_id){  
            $price +=  $value['product']['advanced_price'] * $value['qty'];
		}
     }
     return $price;
  }

    /**
     * 返回用户得的优惠码
     * @param varchar $coupon 
     */
    public static function christmas_coupon_code($coupon)
    {
        $christmas_result_db = D('christmas_result');
        $where = array(
            'prize_content' => $coupon,
        );
        return $christmas_result_db->field('id,prize_type,prize_content,coupon_used')->where($where)->find();
    }
	
	/**
     * 把优惠码设为使用过
     * @param varchar $coupon 
     */
    public static function christmas_coupon_used($coupon)
    {
        $christmas_result_db = D('christmas_result');
        $where = array(
            'prize_content' => $coupon,
        );
        return $christmas_result_db->where($where)->save(array('coupon_used'=>1));
    }
	
	/**
     * 读出特殊商品的总金额
     * @param float $total_amount 
     */
    public static function special_total_amount()
    {
		$special_product = CartModel::get_cart_product_list(false, 0, array('neq',0));
		return $special_product['total_amount'];
    }	

	/**
     * 获取商品的定制数据
     * int $pid 商品id
     * varchar $attrData 已选择的定制数据
     * booler $cache 是否放入缓存
     * @param array $attributeList $size_type
     */	
	public static function cart_attr_show($pid, $attrData = '', $sid,$cache = false){
        global $user,$language_id;$language_id=6;
	    //产品属性
		$attributeList = ProductModel::get_product_custom_attribte_list($pid, array('attr_sell' => 0),$language_id);// 获得商品的规格和属性
		
		$count_attributeList = count($attributeList)-4;
        
        $customArray = array();
        $customArray[$pid] = !empty($attrData) ? unserialize($attrData) : NULL;
		
		foreach($customArray[$pid] as $vc){
			if(in_array($vc['attr_id'],array(54,70,112,134))){
				$new_custom_arr[$vc['attr_value_id']]=$vc['attr_id'].":".$vc['attr_name'].":".$vc['product_attr_id'].":".$vc['attr_value'].":".$vc['attr_value_id'];
			}else{
				$new_custom_arr[$vc['attr_id']]=$vc['attr_id'].":".$vc['attr_name'].":".$vc['product_attr_id'].":".$vc['attr_value'].":".$vc['attr_value_id'];
			}
		}
		
		$customArray[$pid] =$new_custom_arr;
		
        $size_type = array();
		$arrtlist = array();
		$fontLocation = 0;
		$custom_more = false;
		foreach ($attributeList as $attr_id => $attr){
			//字体整体放的位置
			if($attr['attr_pro_fid'] == '9999' && $fontLocation == 0){
				$arrtlist[] = 9999;
				$fontLocation = $attr_id;
			}
			$arrtlist[] = $attr_id;
            //查询是否有更多定制选项
			if($attr['attr_pro_fid'] == 0 && $attr['attr_custom'] == '0'){
                $custom_more = true;
			}
            //收集size_type
			if($attr['size_type'] > 0 && !in_array($attr['size_type'], $size_type)){
				$size_type[] = $attr['size_type'];
			}
		}
		
        $special_custom = array();//非常规选项
        //取默认值
        if($customArray){
	 		foreach ($customArray[$pid] as $attr_id => $pattrArr){
	 			if(!in_array($attr_id, $arrtlist)){
	 				if($pattrArr){
	 					$special_custom[] = $attr_id;
	 				}
	 				continue;
	 			}
				$attrArr = explode(':', $pattrArr);
				//解决绣字问题显示数字问题 30:Monogram:850068::0 
				if($attrArr[2]=='' || ($attrArr[3]=='' && $attrArr[4] ==0)){
					$attributeList[$attr_id]['default'] = $attrArr[3];
				}else{
					//修正产品与定制选项绑定id修改时 id变化产生的问题
					$default = '';
					foreach ($attributeList[$attr_id]['values'] as $values) {
						if($values['attr_value_id'] == $attrArr[4]){
							$default = $values['product_attr_id'];break;
						}     
					}
					//解决当产品不勾选此地址选项是，可以让客户看到原先的定制选项
					if($attributeList[$attr_id]['values'] && !$default && $attrArr[4]){
						$this_values = D('attribute_values')->where(array('id'=>$attrArr[4]))->find();
						$this_values_items = D('attribute_values_items')->Field('attr_value,attr_content')->where(array('att_value_id'=>$attrArr[4],'language_id'=>$language_id))->find();
                        $default = 'old'.$this_values['id'];
                        $attributeList[$attr_id]['values'][] = array(
                            'label' => $this_values_items['attr_value'],
                            'image' => $this_values['attr_img'],
                            'image2' => $this_values['attr_img2'],
                            'libu_img'=>$this_values['libu_img'],
                            'product_attr_id' => $default,
                            'attr_value_id' => $this_values['id'],
                            'attr_content' => $this_values_items['attr_content'],
                            'sort_order' => $this_values['sort_order'],
                            'add_money' => $this_values['add_money'],
                        	);
					}
					$attributeList[$attr_id]['default'] = $default;
				}
			}       	
        }

        $attrSelect = array();
		foreach ($attributeList as $attr_id => $attr){	
			$is_exclude = false;
			
			if(in_array($attr_id,array(55,59,91,71,74,120,113,116,118,114,115,57,58,72,73,64,65))){//去除笔袋，袖衬贴布 插花眼等的默认值
				$is_exclude = true;
				if(!isset($customArray[$pid])){
					$attributeList[$attr_id]['default'] = '';
				}
			}
            
            //缓存里已删除的定制选项，删除默认值
			if($customArray[$pid] && !$customArray[$pid][$attr_id] && $attributeList[$attr_id]['default']){
				$attributeList[$attr_id]['default'] = '';
			}

            //54,70,112,134 more option 
			$option_default_id = array();
			if(in_array($attr_id,array(54,70,112,134))){
                $option_default_id = explode('|', $attr['default']);
			}
			foreach ($attr['values'] as $z_key =>$attrv){
				//修复BUG 后台定制属性 有值 但名字为空 
				$attr_value = $attr_id.':'.$attr['name'].':'.$attrv['product_attr_id'] .':'. $attrv['label'] .':'. $attrv['attr_value_id'];
				//$attributeList[$attr_id]['values'][$z_key]['attr_value'] = $attr_value;
                //图片加链接
                $attributeList[$attr_id]['values'][$z_key]['image']  = $attrv['image']  ? $attrv['image']  : '';
                $attributeList[$attr_id]['values'][$z_key]['image2'] = $attrv['image2'] ? $attrv['image2'] : '';
                
				if(($attr['default'] == $attrv['product_attr_id']) && !$is_exclude && !isset($customArray[$pid])){
					if($attr['attr_pro_type'] != 1 && !in_array($attr_id,array(54,70,112,134))) 
						$attrSelect[$attr_id] = $attr_value;
				}

                //54,70,112,134 more option 
                if(is_array($option_default_id) && !isset($customArray[$pid])){
                	if(in_array($attrv['product_attr_id'], $option_default_id)){
                        $attrSelect[$attrv['attr_value_id']] = $attr_value;
                	}
                }
				//鞋子常用尺码 初始尺码值 （无数据给默认值）
	            if($attr_id == 161 && !isset($customArray[$pid]) && $attr['default'] == $attrv['product_attr_id']){
	            	$size_value = 0;
	            	if($attrv['attr_value_id'] == 895){
                        $size_value = C('shoe_size_us_default');
	            	}else if($attrv['attr_value_id'] == 894){
                        $size_value = C('shoe_size_eu_default');
	            	}
	            	//162:尺码值::8.5
	            	$attrSelect[162] = '162:'.$attributeList[162]['name'].'::'.$size_value;
	            }                
			}

			//取默认图
			if(in_array($attr_id, array(55,71,113))){
				$attributeList[$attr_id]['attr_content'] = L('penbag_option');
				$attributeList[$attr_id]['image'] = '/statics/front/images/custom/bidai.jpg';
			}else if(in_array($attr_id, array(91,118,120))){
				$attributeList[$attr_id]['attr_content'] = L('_Boutonniere_');
				$attributeList[$attr_id]['image'] = '/statics/front/images/custom/chahuayan.jpg';
			}else if(in_array($attr_id, array(59,74,116))){
				$attributeList[$attr_id]['attr_content'] = L('_zhoucuntiebu_');
				$attributeList[$attr_id]['image'] = '/statics/front/images/custom/zhoucuntiebu.jpg';
			}else if(in_array($attr_id, array(57,72,114))){
				$attributeList[$attr_id]['attr_content'] = L('_suoyanxian_');
				$attributeList[$attr_id]['image'] = '/statics/front/images/custom/suoyanxian.jpg';
			}else if(in_array($attr_id, array(58,73,115))){
				$attributeList[$attr_id]['attr_content'] = L('_lingdini_');
				$attributeList[$attr_id]['image'] = '/statics/front/images/custom/lingdini.jpg';
			}

			//处理option多默认
			if($attr['attr_pro_type']==4){
				$attributeList[$attr_id]['attr_content'] = '';
				$attributeList[$attr_id]['attr_help'] = L('change_the_default_options');
                //option修改定制时取用户选好的定制项
                if(isset($customArray[$pid])){
	                $option_default = '';
	                if($special_custom){
						foreach ($attr['values'] as $z_key =>$attrv){
							if(in_array($attrv['attr_value_id'], $special_custom)){
								$option_default .= $option_default ? '|'.$attrv['product_attr_id'] : $attrv['product_attr_id'];
							}
						}                	
	                }
	                $attributeList[$attr_id]['default'] = $option_default;
                }
			}
            //去掉radio和图片选择默认项
            if(isset($customArray[$pid])){
	            if(in_array($attr['attr_pro_type'], array(3,5))){
	                if(!isset($customArray[$pid][$attr_id])){
	                    $attributeList[$attr_id]['default'] = '';
	                }
	            }
            }

			//去除绣字的默认值 (鞋子的尺码值除外)
            if($attr['attr_pro_type'] == 1 && !isset($customArray[$pid]) && $attr_id != 161){
            	$attributeList[$attr_id]['default'] = '';
            }
		}
        
        //读字体
        if($fontLocation>0){
        	//$attr_help = AttributeModel::attribute_info($fontLocation);
        	$attributeList['9999'] = array(
                "attr_id" => "9999",
                "name" => L('jacket_monogram'),
                "attr_content" => "",
                "attr_pro_type" => "0",
                "attr_pro_fid" => "0",
                "attr_pro_sort" => "999",
                //"attr_help" => $attr_help, 
                "attr_custom" => "2",
                "values" => array(),
                "default" => "",
        	);
        }
		//选择了缓存
		if($cache){
			
			$customArrayCache = array();
			if(session('custom_admin'))
			    $customArrayCache = unserialize(base64_decode(session('custom_admin')));
	        //放进缓存
	        //新加的时候存$attrSelect ,修改的时候存$customArray[$pid]，
	        $customArrayCache[$pid] = $customArray[$pid] ? $customArray[$pid] : $attrSelect;
	        if(is_array($customArrayCache[$pid])){
				//如果插花眼是无，则插花眼撞色无
				if(isset($customArrayCache[$pid]['91'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['91']);
					if(isset($attrval_array[4]) && $attrval_array[4]==1147){
						unset($customArrayCache[$pid][57]);
					}
				}
				if(isset($customArrayCache[$pid]['118'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['118']);
					if(isset($attrval_array[4]) && $attrval_array[4]==1148){
						unset($customArrayCache[$pid][114]);
					}
				}
				if(isset($customArrayCache[$pid]['120'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['120']);
					if(isset($attrval_array[4]) && $attrval_array[4]==864){
						unset($customArrayCache[$pid][72]);
					}
				}
				//马甲领型U型领，则无马甲手巾袋
				if(isset($customArrayCache[$pid]['105'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['105']);
					if(isset($attrval_array[4]) && $attrval_array[4]==316){
						unset($customArrayCache[$pid][202]);
					}
				}
				if(isset($customArrayCache[$pid]['126'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['126']);
					if(isset($attrval_array[4]) && $attrval_array[4]==604){
						unset($customArrayCache[$pid][229]);
					}
				}
				//衬衫撞色
				if(isset($customArrayCache[$pid]['228'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['228']);
					if(isset($attrval_array[4]) && $attrval_array[4]==1273){
						unset($customArrayCache[$pid][89]);
					}
				}
				//选择无里时，不可以选择里布颜色 (单西)  
				if(isset($customArrayCache[$pid]['68'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['68']);
					if(isset($attrval_array[4]) && $attrval_array[4]==855){
						unset($customArrayCache[$pid][69]);
					}
				}
				//领型为909,1304,1125,1283,则显示领口部撞色
				if(isset($customArrayCache[$pid]['56'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['56']);
					if(isset($attrval_array[4]) && !in_array($attrval_array[4],array(909,1304,1125,1283))){
						unset($customArrayCache[$pid][230]);
					}
				}
				//袖口为905时，则袖口撞色
				if(isset($customArrayCache[$pid]['75'])){
					$attrval_array=explode(":",$customArrayCache[$pid]['75']);
					if(isset($attrval_array[4]) && !in_array($attrval_array[4],array(905))){
						unset($customArrayCache[$pid][231]);
					}
				}
			}
			
			$custom_cookie = base64_encode(serialize($customArrayCache));
			session('custom_admin', $custom_cookie);
	 		$cacheId = 'sel_custom_val_'.$sid;
			S($cacheId, $customArrayCache);			
		}

        // echo "<pre />";
        // print_r($customArray[$pid]);
        // print_r($attributeList);exit;
        $option = array(
            'arrtlist' => $arrtlist,
            'custom_more' => $custom_more,
            'fontLocation' => $fontLocation,
        	);

        return array($attributeList,$size_type,$option);
	}
	
	//购物车推荐商品
	public static function Recommend($product_id){
        $model = array(
			'product.model_id = 14', //衬衫
			'product.model_id = 1 or product.model_id = 22',//单西&风衣
			'product.model_id = 21 or product.model_id = 20', //单裤,马甲
			'product.model_id = 16', //配饰
            'product.model_id = 2 or product.model_id = 18 or product.model_id = 23',//套装                        
        	);
        $productId = array();
	  	foreach ($model as $val){	  		   
	  		$qtysRes = self::select_qtys($val, $product_id);
		  	if($product_id){
		  		$oneid = array();
		        foreach($qtysRes as $v){
		        	$oneid[] = $v['product_id'];
		        }
		  		if(count($oneid) < 2){
			        $sql = 'select product.id from product as product
							where product.display  = 1 and ('.$val.') and (product.id not in ('.implode(',',array_merge($oneid,$product_id)).')) ORDER BY visit DESC limit 0,'.(2-count($oneid));
			        $res = M()->query($sql);
			        foreach($res as $v){
	                   $oneid[] = $v['id'];
			        }
		  		}
		  		foreach ($oneid as $v) {
		  			$productId[] = $v;
		  		}
		  	}else{
		  		$productId = array();
		  		foreach($model as $val){
		  			$qtysRes = self::cart_qtys($val);
		  			$oneid = array();
		  			foreach($qtysRes as $v){
		  				$oneid[] = $v['product_id'];
		  			}
		  			if(count($oneid) < 2){
		  				$sql = 'select product.id from product as product
							where product.display  = 1 and ('.$val.') and (product.id in ('.implode(',',array_merge($oneid)).')) ORDER BY visit DESC limit 0,'.(2-count($oneid));
			       		 $res = M()->query($sql);
				       	foreach($res as $v){
		                   $oneid[] = $v['id'];
				        }	
		  		    }
			  		foreach ($oneid as $v) {
			  			$productId[] = $v;
			  		}
		  		}
		  	}
		}

	  	return $productId;
	}
	public static function cart_qtys($model_id_str){
        
        $sql = 'select items.product_id,sum(qty) as qtys from orders_items as items 
		        LEFT JOIN orders as orders on(items.order_id = orders.id) 
		        where items.product_id in(select product.id from product as product
				where product.display  = 1 and ('.$model_id_str.') ) and orders.payment_status = 1 
				GROUP BY items.product_id ORDER BY qtys DESC limit 0,2';
        $res = M()->query($sql);
        return $res;
       
	}
	public static function select_qtys($model_id_str, $product_id){
        
        $sql = 'select items.product_id,sum(qty) as qtys from orders_items as items 
		        LEFT JOIN orders as orders on(items.order_id = orders.id) 
		        where items.product_id in(select product.id from product as product
				where product.display  = 1 and ('.$model_id_str.') and (product.id not in ('.implode(',',$product_id).')) ) and orders.payment_status = 1 
				GROUP BY items.product_id ORDER BY qtys DESC limit 0,2';
        $res = M()->query($sql);
        return $res;
       
	}

	/**
	 *partner获取购物车中商品列表
	 *@param boolean $is_collect 是否为收藏产品
	 */
	public static function get_cart_product_list_partner($is_collect = false,$attribute_type=0,$pro_type='all')
	{
		global $user;
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		}else{
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}

		$where['is_collect'] = $is_collect ? 1 : 0;
		if($attribute_type){
			$where['car_type'] = 1;
		}else{
			$where['car_type'] = 0;
		}

		if(strval($pro_type) != 'all'){
			$where['pro_type'] = $pro_type;
		}
		
		$cart_db = D('cart_products_partner');
		$cartInfo = array(
			'total_weight' => 0,
			'total_amount' => 0,
			'total_number' => 0,
			'is_custom' => false,
			'total_amount_normal' => 0,
		);

		$cartList = $cart_db->where($where)->order('id DESC')->select();
		//echo $cart_db->getLastSql()."<br>";
		// echo "<pre />";
		// echo print_r($cartList);exit;
		if($cartList){
			foreach ($cartList as &$cart){
				if($cart['pid']){
					$attr = unserialize($cart['attr']);
					$product = ProductModel::get_product_info($cart['pid']);
					//dump($product);exit;
					//**兼容原先数据  
					$product['price'] = ProductModel::get_final_price($cart['pid'], $cart['qty'], true, $attr, $cart['custom_type']);
					if($attribute_type){
						$product['goods_amount']  = $product['sell_price'] * $cart['qty'];
						$product['price'] = $product['sell_price'];
					}else{
						$product['goods_amount']  = $product['price'] * $cart['qty'];
					}  
                    //**兼容原先数据
					if($cart['price'] > 0 || $cart['pro_type'] > 0){ //兼容原先数据
						//使用购物车里的价格
						$product['price'] = $cart['price'];
	                    $product['goods_amount']  = $cart['price'] * $cart['qty'];  
					}

					$product['goods_weight']  = $product['weight'] * $cart['qty'];
					$product['goods_dingjin'] = $product['yufu_price'] * $cart['qty'];
					
						if($cart['car_type'] == 0){
							$product['goods_dingjin'] = 0;
						}
					
						if($cart['custom_type'] && is_array($attr)){
							$attrList = array();
							foreach ($attr as $attrv){
								$attr2 = explode(':', $attrv);
								$attrList[] = array(
									'attr_id' => $attr2[0],
									'attr_name' => $attr2[1],
									'product_attr_id' => $attr2[2],
									'attr_value' => $attr2[3],
								);
							}
							$product['attr'] = $attrList;
							$cartInfo['is_custom'] = true;
						}else{
							$product['attr'] = AttributeModel::get_product_attribute_List($attr);
						}
						
						//两件套 三件套 增加 附加裤子
						if(in_array($product['model_id'], array(2,18)) && $product['add_more'] == 1){
							$add_more_product = array();
							$add_more_product['name']  =  L('addPants');
							$add_more_product['price'] =  $product['pants_price'];
							$cart['add_pants'] = $add_more_product;
							if($cart['pants_qty'] > 0){
								$cartInfo['total_amount']  += $product['pants_price'] * $cart['pants_qty'];
								$cartInfo['total_amount_normal']  += $product['pants_price'] * $cart['pants_qty'];
							}
					    }else{
					    	if($cart['pants_qty'] > 0){
                                D('cart_products')->where(array('id'=>$cart['id']))->save(array('pants_qty'=>0));
					    		$cart['pants_qty'] = 0;
					    	}
					    }

						$cart['product'] = $product;
						$cartInfo['total_weight']  += $product['goods_weight'];
						$cartInfo['total_amount']  += $product['goods_amount'];
						$cartInfo['total_dingjin'] += $product['goods_dingjin'];
						if(!$cart['car_type'])
							$cartInfo['total_number']  += $cart['qty'];
                        if($cart['pro_type'] == 0){
                        	$cartInfo['total_amount_normal']  += $product['goods_amount'];
                        } 
						
					
				}
			}
			unset($cart);
	
			$cartInfo['productList'] = $cartList;
		}
	
		if(!$is_collect){
			$_SESSION['cart']['number'] = $cartInfo['total_number'];
			$_SESSION['cart']['amount'] = $cartInfo['total_amount'];
		}
		return $cartInfo;
	}

	/**
	 * 删除购物车中的商品
	 * @param int $cart_id 购物车ID号
	 */
	public static function delete_cart_product_partner($cart_id)
	{
		global $user;
		$where = array(
			//'user_id' => isset($user['id']) ? $user['id'] : 0,
			'id' => is_array($cart_id) ? array('IN', join(',', $cart_id)) : $cart_id,
		);
		$cart_db = D('cart_products_partner');
		$cart_db->where($where)->delete();
	}

	/**
	 * 根据商品ID获取购物车中单个商品的信息
	 * @param int $pid 商品ID
	 * @param array $attr 商品属性
	 * @param int $custom_type 定制类型
	 * @param int $pro_type 类型 0为正常商品
	 */
	public static function get_cart_product_info_by_pid_partner($pid, $attr, $custom_type=0, $pro_type=0)
	{
		global $user;
		$pid = intval($pid);
		$cart_db = D('cart_products_partner');
		if(!$pid && empty($data)){
			return false;
		}
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		} else {
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}
		if($pid){
			$where['pid'] = $pid;
		}
		if($attr){
			$where['attr'] = serialize($attr);
		}
		if($custom_type){
			$where['custom_type'] = intval($custom_type);
			$where['car_type'] = 0;
		}
		//if($pro_type){
			$where['pro_type'] = $pro_type;
		//}
		$cartInfo = $cart_db->where($where)->find();
		return $cartInfo;
	}

	/**
	 * 获取购物车中单个商品的信息
	 * @param int $cart_id 购物车ID
	 */
	public static function get_cart_product_info_by_id_partner($cart_id)
	{
		$cart_id = intval($cart_id);
		if(!$cart_id) return false;
		
		$cart_db = D('cart_products_partner');
		$cartInfo = $cart_db->where(array('id' => $cart_id))->find();
		return $cartInfo;
	}

	/**
	 * 更新购物车商品信息
	 * @param int $cart_id 购物车ID
	 * @param float $price 单件价格
	 * @param int $qty 购买商品数量
	 */
	public static function update_cart_product_info_partner($cart_id, $qty, $price, $add_pants=false, $attr=NULL)
	{
		$affected = false;
		$cart_db = D('cart_products_partner');
		$cartInfo = self::get_cart_product_info_by_id_partner($cart_id);
		if($cartInfo){
			if(!$add_pants){
				$data['qty'] = $qty;
               	$data['price'] = $price;
			}else{
                $data['pants_qty'] = $qty;
			}
			$data['add_time'] = time();
		    if($attr&&is_array($attr)){
		    	$data['attr'] = serialize($attr);
		    }else{
                $data['attr'] = $attr;
            }
			$affected = $cart_db->where(array('id' => $cart_id))->save($data);
		}
		return $affected;
	}

	/**
   * 新增商品到购物车
   * @param array $post
   */
	public static function insert_product_to_cart_partner($post)
	{
		global $user;
		$data = array(
			'sid' => $user['sid'],
			'user_id' => isset($user['id']) ? $user['id'] : 0,
			'pid' => isset($post['pid']) ? intval($post['pid']) : 0,
      		'qty' => isset($post['qty']) ? intval($post['qty']) : 1,
			'custom_type' => isset($post['custom_type']) ? intval($post['custom_type']) : 0,
      		'add_time' => time(),
			'chima' => trim($post['chima']),
			'car_type' => trim($post['car_type']),
      		'attr' => isset($post['attr']) && $post['attr'] ?  serialize($post['attr']) : null,
			'measure_id' => isset($post['measure_id']) ? intval($post['measure_id']) : 0,
			'match_id' => isset($post['match_id']) ? intval($post['match_id']) : 0,
			'measure_id' => $post['measure_id'],
			'pro_type' => $post['pro_type'],
			'price' => $post['price'],
		);
		$cart_db = D('cart_products_partner');
		$last_id = $cart_db->add($data);
		return $last_id;
	}		
}